package com.sqlcheck.controller;

import com.sqlcheck.common.Result;
import com.sqlcheck.dto.request.LoginRequest;
import com.sqlcheck.dto.response.LoginResponse;
import com.sqlcheck.dto.response.CurrentUserResponse;
import com.sqlcheck.service.AuthService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Tag(name = "用户认证管理", description = "员工登录、登出、用户信息管理等认证相关功能")
public class AuthController {

    private final AuthService authService;

    @PostMapping("/login")
    @Operation(summary = "员工登录", description = "使用6位数字工号和密码进行登录，新员工自动注册")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "登录成功", content = @Content(schema = @Schema(implementation = LoginResponse.class))),
            @ApiResponse(responseCode = "400", description = "登录失败，工号格式错误或密码错误"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<LoginResponse> login(
            @Valid @RequestBody @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "登录请求信息", required = true, content = @Content(schema = @Schema(implementation = LoginRequest.class))) LoginRequest loginRequest) {

        try {
            log.info("收到员工登录请求: employeeId={}", loginRequest.getEmployeeId());

            LoginResponse response = authService.login(loginRequest);

            log.info("员工登录成功: employeeId={}, userId={}",
                    loginRequest.getEmployeeId(), response.getUserInfo().getId());

            return Result.success(response);

        } catch (IllegalArgumentException e) {
            log.warn("员工登录失败: employeeId={}, error={}",
                    loginRequest.getEmployeeId(), e.getMessage());
            return Result.error(e.getMessage());

        } catch (Exception e) {
            log.error("员工登录异常: employeeId={}",
                    loginRequest.getEmployeeId(), e);
            return Result.error("登录服务异常，请稍后重试");
        }
    }

    @GetMapping("/me")
    @Operation(summary = "获取当前用户信息", description = "根据访问令牌获取当前登录用户的详细信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = CurrentUserResponse.class))),
            @ApiResponse(responseCode = "401", description = "未授权，token无效或已过期"),
            @ApiResponse(responseCode = "404", description = "用户不存在")
    })
    public Result<CurrentUserResponse> getCurrentUser(
            @Parameter(description = "访问令牌", required = true) @RequestHeader("Authorization") String authHeader) {

        try {
            // 从Authorization header中提取token
            String token = extractTokenFromHeader(authHeader);
            if (token == null) {
                return Result.error("无效的Authorization头格式");
            }

            CurrentUserResponse response = authService.getCurrentUser(token);
            return Result.success(response);

        } catch (IllegalArgumentException e) {
            log.warn("获取用户信息失败: {}", e.getMessage());
            return Result.error(e.getMessage());

        } catch (Exception e) {
            log.error("获取用户信息异常", e);
            return Result.error("获取用户信息异常，请稍后重试");
        }
    }

    @PostMapping("/logout")
    @Operation(summary = "退出登录", description = "用户退出登录，使当前token失效")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "退出成功"),
            @ApiResponse(responseCode = "401", description = "未授权，token无效")
    })
    public Result<Void> logout(
            @Parameter(description = "访问令牌", required = true) @RequestHeader("Authorization") String authHeader) {

        try {
            String token = extractTokenFromHeader(authHeader);
            if (token == null) {
                return Result.error("无效的Authorization头格式");
            }

            authService.logout(token);
            return Result.success();

        } catch (Exception e) {
            log.error("退出登录异常", e);
            return Result.error("退出登录异常，请稍后重试");
        }
    }

    @GetMapping("/validate")
    @Operation(summary = "验证token有效性", description = "验证访问令牌是否有效")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "验证完成"),
            @ApiResponse(responseCode = "401", description = "token无效")
    })
    public Result<Boolean> validateToken(
            @Parameter(description = "访问令牌", required = true) @RequestHeader("Authorization") String authHeader) {

        try {
            String token = extractTokenFromHeader(authHeader);
            if (token == null) {
                return Result.success(false);
            }

            boolean isValid = authService.validateToken(token);
            return Result.success(isValid);

        } catch (Exception e) {
            log.error("验证token异常", e);
            return Result.success(false);
        }
    }

    /**
     * 从Authorization header中提取token
     * 支持格式：Bearer {token}
     */
    private String extractTokenFromHeader(String authHeader) {
        if (authHeader == null || authHeader.trim().isEmpty()) {
            return null;
        }

        if (authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }

        // 直接返回token（向后兼容）
        return authHeader;
    }
}